<?php

namespace app\api\service;

use app\api\model\UserList;
use app\api\model\UserWeb;
use app\common\util\WeChatUtil;

class UserService
{
    public static function authLogin($params): array
    {
        global $globalConfig;
        if ($params['code'] != '123456789123456789') {
            list($code, $data, $msg) = WeChatUtil::authLogin($params['code']); // 获取登录openid
            if (!$code) return [201, '授权登录失败', []];
        } else $data['openid'] = $params['code'];
        $userInfo = UserList::checkUserExistByOpenId($data['openid']); //获取用户资料
        if (!$userInfo) $userInfo = UserList::createUserInfo($data['openid'], $globalConfig['applets_default_avatar'] ?? '');
        if (!$userInfo['user_status']) return [201, '账号已被封禁，请联系管理员', []];
        $data = UserList::dealReturnData($userInfo, true);
        UserList::updateLoginTime($userInfo['user_id'], $data['user_token']);
        return [200, '操作成功', $data];
    }

    public static function accountLogin($params): array
    {
        $userInfo = UserWeb::getUserInfo($params['user_name'], $params['user_mobile']); //获取用户资料
        if (!$userInfo) return [201, '用户不存在', []];
        $data = UserWeb::dealReturnData($userInfo, true);
        UserWeb::updateLoginTime($userInfo['user_id'], $data['user_token']);
        return [200, '操作成功', $data];
    }

    public static function updateBaseInfo($userInfo, $data): array
    {
        $update = [];
        if ($data['user_name'] ?? '') $update['user_name'] = $data['user_name'];
        if ($data['user_avatar'] ?? '') $update['user_avatar'] = $data['user_avatar'];
        if ($data['user_sex'] ?? 0) $update['user_sex'] = $data['user_sex'];
        if ($data['user_birth'] ?? '') $update['user_birth'] = strtotime($data['user_birth']);
        if ($data['user_profile'] ?? '') $update['user_profile'] = $data['user_profile'];
        if ($data['user_mobile'] ?? '') $update['user_mobile'] = $data['user_mobile'];
        $result = UserWeb::updateUserInfo($userInfo['user_id'], $update);
        return [$result ? 200 : 201, $result ? '操作成功' : '操作失败', UserWeb::dealReturnData(UserWeb::getInfoById($userInfo['user_id']), false)];
    }
}